package cuppics;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;

import org.junit.Test;

public class Prj7 {

	/**
	 * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
	 * see that the 6th prime is 13.
	 * 
	 * What is the 10 001st prime number?
	 */
	@Test
	public void test() {
		System.out.println(new PrimeMaster().calcultePrimeList100().toString());
		System.out.println(new PrimeMasterLoop().loop2Limit(10001));
	}

	public static class PrimeMaster {

		public List<Integer> primeListIn100 = new ArrayList<Integer>();

		public PrimeMaster calcultePrimeList100() {

			primeListIn100.clear();

			int upLimit = 100;
			BitSet bs = new BitSet(upLimit);

			boolean init = true;

			while (true) {
				int val = getNonSetVal(init, bs, primeListIn100, upLimit);
				init = false;

				for (int i = val + 1; i < upLimit; i++) {
					if (i % val == 0) {
						bs.set(i);
					}
				}

				if (val < 0) {
					break;
				}
			}

			for (int i = 2; i < upLimit; i++) {

				if (!bs.get(i)) {
					primeListIn100.add(i);
				}
			}

			return this;
		}

		private int getNonSetVal(boolean init, BitSet bs,
				List<Integer> primeListIn1002, int upLimit) {

			if (init) {
				primeListIn1002.add(2);
				bs.set(2);
				return 2;
			}

			for (int i = 3; i < upLimit; i++) {
				if (!bs.get(i)) {
					bs.set(i);
					primeListIn1002.add(i);
					return i;
				}
			}
			return -1;
		}

		@Override
		public String toString() {

			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < primeListIn100.size(); i++) {
				sb.append(primeListIn100.get(i) + ",");
			}
			sb.append("\n");

			return sb.toString();
		}

	}

	public static class PrimeMasterLoop {

		public List<Integer> dataList = new ArrayList<Integer>();

		public PrimeMasterLoop() {
			dataList = new PrimeMaster().calcultePrimeList100().primeListIn100;
		}

		public int loop2Limit(int countLimit) {


			int startNumVal = 100;
			int endNumVal = startNumVal * startNumVal;

			while (dataList.size() < countLimit) {

				for (int i = startNumVal + 1; i <= endNumVal; i = i + 2) {
					boolean isPrime = true;
					for (int j = 0; j < dataList.size(); j++) {

						int prime = dataList.get(j);
						if (i % prime == 0) {
							isPrime = false;
							break;
						}
					}
					if (isPrime) {
						dataList.add(i);
						// System.out.println("[" + dataList.size() + "]=" + i);
						if (dataList.size() >= countLimit) {
							break;
						}
					}
				}
				startNumVal = endNumVal;
				endNumVal = endNumVal * endNumVal;
			}

			// StringBuilder sb = new StringBuilder();
			// for (int i = 0; i < dataList.size(); i++) {
			// sb.append(dataList.get(i) + ",");
			// if ((i + 1) % 20 == 0) {
			// sb.append("\n");
			// }
			// }
			// sb.append("\n");
			//
			// System.out.println(sb.toString());

			return dataList.get(countLimit - 1);

		}

	}
}
